package demo5;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.PriorityQueue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: asus
 * Date: 2024-12-18
 * Time: 16:52
 */
public class Media {
    List<Integer> list = new ArrayList<>();
    public void Insert(Integer num) {
        int i = 0;
        for (; i < list.size(); i++) {
            if (num <= list.get(i)) {
                break;
            }
        }
        list.add(i, num);
    }

    public Double GetMedian() {
        int index = list.size() / 2;
        if (list.size() % 2 == 1) {
            return list.get(index) * 1.0;
        }
        return (list.get(index)*1.0 + list.get(index-1)*1.0) / 2;
    }

    PriorityQueue<Integer> left = new PriorityQueue<>((o1, o2) -> o2 - o1);
    PriorityQueue<Integer> right = new PriorityQueue<>();
    public void Insert2(Integer num) {
        left.offer(num);
        right.offer(left.poll());
        if (left.size() < right.size()) {
            left.offer(right.poll());
        }
    }

    public Double GetMedian2() {
        if (left.size() == right.size()) {
            return (left.peek()*1.0 + right.peek()*1.0) / 2;
        } else {
            return left.peek()*1.0;
        }
    }

    public static void main(String[] args) {
        Media media = new Media();
        int[] arr = new int[]{5,2,3,4,1,6,7,0,8};
        for (int i = 0; i < 9; i++) {
            media.Insert(arr[i]);
            System.out.println(media.GetMedian());
        }
    }
}
